<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/21
 * Time: 17:19
 */

namespace app\manage\controller;


class PosterSpace extends Base
{
    private $mod;
    protected $beforeActionList = [
      'beforeIndex'  => ['only' => 'index'],
        'beforeEdit' => ['only' => 'add,edit']
    ];
    public function _initialize() {
        parent::_initialize();
        $this->mod = model('poster_space');
    }
    public function beforeIndex(){
        $big_menu = array(
            'title' => '添加广告位',
            'iframe' => url('PosterSpace/add'),
            'id' => 'add',
            'width' => '500',
            'height' => '280'
        );
        $this->_ajaxedit = 1;
        $this->_data = array(
            'addspace'    => [
                'c' => 'Poster',
                'a' => 'add',
                'str'    => '<a href="%s">添加广告</a>',
                'param' => array('space_id'=>'@id@','menuid'=>37),
                'isajax' => 0,
                'replace'=> ''
            ],
            'addlist'    => [
                'c' => 'Poster',
                'a' => 'index',
                'str'    => '<a href="%s">广告列表</a>',
                'param' => array('space_id'=>'@id@','menuid'=>37),
                'isajax' => 0,
                'replace'=> ''
            ],
        );
        $this->assign('big_menu', $big_menu);
    }
    public function beforeEdit(){
        $type = $this->mod->typeArr();
        $this->assign('type_list',$type);
    }
    public function delete(){
        //注册前置事件 如果该广告位下有广告则不能删除
        \app\common\model\PosterSpace::event('before_delete',function($obj){
            if($obj->items > 0){
                return false;
            }
            return true;
        });
        parent::delete();
    }
    /**
     * 检查名称是否有重复
     */
    public function ajaxCheckName() {
        $name = input('param.name');
        $id = input('param.id/d');
        if ($this->name_exists($name,$id)) {
            $this->ajaxReturn(0, '广告位已存在');
        } else {
            $this->ajaxReturn(1);
        }
    }

    private function name_exists($name,$id=0){
        $pk = $this->mod->getPk();
        $where['name'] = $name;
        $id && $where[$pk]    = ['neq',$id];
        $result=$this->mod->where($where)->count($pk);
        if($result){
            return 1;
        }else{
            return 0;
        }
    }
}